package com.fyyg.common.wechat;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.List;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
//import net.sf.json.JSONArray;
//import net.sf.json.JSONObject;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;

public class WeChatSendMessage {

	
	/** 错误信息 */
	private static String errmsg = "";

	/** 错误码 */
	private static String errcode = "";
	
    private final static Logger log = LogManager.getLogger(WeChatSendMessage.class);

	private static HttpClient httpclient = new DefaultHttpClient(new ThreadSafeClientConnManager());
	
	private HashMap<String, String> varMap=new HashMap<String, String>();//变量集合
	private List<String> dyncVal;     // 变量集合
	String param="";
	String[] parArray=null;
	private static final String  APP_ID ="wxf438f36b6faf41de";//WeChatObject.MCH_APPID; 	
	private static final String  APPSECRET ="d34ec8d38f97603a54dc8636f94b69d1";//WeChatObject.MCH_APPSECRET; 									//服务号AppSecret
	private static final String  SNSAPI_USERINFO_URL="https://open.weixin.qq.com/connect/oauth2/authorize"; //获取code链接地址
	private static final String  ACCESS_TOKEN_URL="https://api.weixin.qq.com/cgi-bin"; 		//获取access_token链接地址
	private static final String  WX_URL="https://api.weixin.qq.com";
	private static final String templateOrder="-MQLYzxVJIclntEFDmZjKrSq-bC32-3VFNX1btkyoys";

	
	
	private static String getAccessToken() {
		/** 开发者使用凭证 */
		String access_token = "";
		// 微信给的HTTP请求地址
		String url = ACCESS_TOKEN_URL+"/token?grant_type=client_credential&appid=" + APP_ID + "&secret=" + APPSECRET ;
		System.out.println("ACCESS_TOKEN:"+url);
		httpclient = wrapClient(httpclient);
		log.info("url:"+url);
		HttpPost httpget = new HttpPost(url);
		httpget.setHeader("Connection", "close");
		log.info("向微信服务器获取使用凭证");
		StringBuffer buffer = new StringBuffer();
		InputStream is = null;
		BufferedReader in = null;
		try {
			HttpResponse response = httpclient.execute(httpget);

			// 解析返回结果
			HttpEntity rspEntity = response.getEntity();
			if (rspEntity != null) {
				is = rspEntity.getContent();
				in = new BufferedReader(new InputStreamReader(is, "UTF-8"));
				String line = "";
				while ((line = in.readLine()) != null) {
					buffer.append(line);
				}
			}

			if (rspEntity.isStreaming()) {
				EntityUtils.consume(rspEntity);
			}
		} catch (Exception e) {
			log.error("获取使用凭证失败。错误原因：" + e.toString());
		}  finally{  
			if(in !=null){
                try {
                	in.close();
                } catch (IOException e) {
                      e.printStackTrace();
                }
          }
	         if(in !=null){
	                try {
	                	is.close();
	                } catch (IOException e) {
	                      e.printStackTrace();
	                }
	          }
	    }

		String returnStr = buffer.toString();

		System.out.println("returnStr:"+returnStr);
		log.info("接收的返回数据转换为字符串是：" + returnStr);

		// 返回的数据格式是json格式
		// 正确的Json返回结果:
		// {"access_token":"ACCESS_TOKEN","expires_in":7200}
		// 错误的Json返回示例:
		// {"errcode":40013,"errmsg":"invalid appid"}

		JSONObject jsonObject = null;
		try {
			jsonObject =JSONObject.parseObject(returnStr);

			// 判断返回的JSON格式，如果包括access_token，则说明返回的是正确结果，否则返回的是错误结果
			if (jsonObject.containsKey("access_token"))
				access_token = jsonObject.getString("access_token");
			else
				log.error("获取使用凭证失败。错误原因：" + returnStr);

		} catch (Exception e) {
//			log.error("解析微信服务器返回的JSON报文错误。错误原因：" + e.toString());
		}
		System.out.println("access_token:"+access_token);
		return access_token;
	}
	
		/**
		 * 发送图文消息（单图文）
		 */
		public static void sendNew(String str_wxnos,String title,String content,String picUrl,String postUrl,String access_token){
//			String sendMsgUrl=ConfigurationRead.getInstance().getConfigItem("sendMsgUrl");
//			String wxBirthPicurl=ConfigurationRead.getInstance().getConfigItem("wxBirthPicurl");
//			String url = sendMsgUrl + "?access_token=" + access_token;
//			String access_token = "";
			String access_tokenStr = access_token;
			try {
				if(StringUtils.isBlank(access_token))
					access_tokenStr = getAccessToken();
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				log.error("获取开发者凭证信息出错了，错误原因："+e1);
			}
			String url =ACCESS_TOKEN_URL+ "/message/custom/send?access_token=" + access_tokenStr;
			System.out.println("url:"+url);
			httpclient = wrapClient(httpclient);
			HttpPost httppost = new HttpPost(url);
			httppost.setHeader("Connection", "close");
			StringBuffer reqJson =new StringBuffer();

			//str_wxnos="or1vVwH5AVxnRT19skiOXOR739ic;";
			String[] str_wxno = str_wxnos.split(";");
			for(int i=0;i<str_wxno.length;i++){
				
				reqJson.append("{\"touser\":\"");
				reqJson.append(str_wxno[i]);
				reqJson.append("\",");
				reqJson.append("\"msgtype\":\"news\",");
				reqJson.append("\"news\":{\"articles\":[");
				
				reqJson.append("{\"title\":\""+title+"\",");
				reqJson.append("\"description\":");
				reqJson.append("\""+content+"\",");
				reqJson.append("\"picurl\":\"");
				reqJson.append(picUrl+"\",");
				reqJson.append("\"url\":\"");
				reqJson.append(postUrl);
				reqJson.append("\"}");
				
				reqJson.append("\"}");
				
				reqJson.append("]}}");
				log.info(reqJson.toString());
				
				try {
					InputStream stream = new ByteArrayInputStream(reqJson.toString().getBytes("UTF-8"));
					HttpEntity reqEty = new InputStreamEntity(stream, reqJson.toString().getBytes("UTF-8").length);
					httppost.setEntity(reqEty);
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				log.info("向微信服务器发送请求");
				System.out.println("向微信服务器发送请求");
				StringBuffer buffer = new StringBuffer();
				InputStream is  = null;
				BufferedReader in = null;
				try {
					HttpResponse response = httpclient.execute(httppost);
					// 解析返回结果
					HttpEntity rspEntity = response.getEntity();
					if (rspEntity != null) {
						is = rspEntity.getContent();
						in = new BufferedReader(new InputStreamReader(is, "UTF-8"));
						String line = "";
						while ((line = in.readLine()) != null) {
							buffer.append(line);
						}
					}
	               log.info("发送图文返回结果:"+buffer);
	               System.out.println("发送图文返回结果:"+buffer);
					if (rspEntity.isStreaming()) {
						EntityUtils.consume(rspEntity);
					}
				} catch (Exception e) {
					log.error("用户:【"+str_wxno[i]+"】发送图文失败。错误原因：" + e.toString());
				}finally{ 
					if(in !=null){
		                try {
		                	in.close();
		                } catch (IOException e) {
		                      e.printStackTrace();
		                }
		          }
			         if(is !=null){
			                try {
			                	is.close();
			                } catch (IOException e) {
			                      e.printStackTrace();
			                }
			          }
			    }
				
				String returnStr = "[" + buffer + "]";
				log.info("接收的返回数据转换为字符串是：" + returnStr);
				System.out.println("接收的返回数据转换为字符串是：" + returnStr);
				reqJson.delete(0, reqJson.length());//重置 reqJson 清空
			}
			
		}
		
		/**
		 * 获取微信用户信息
		 */
		public static void wxUserInfo(String openId){
			String access_token = "";
			try {
				if(StringUtils.isBlank(access_token))
					access_token = getAccessToken();
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				log.error("获取开发者凭证信息出错了，错误原因："+e1);
			}
			String url =  ACCESS_TOKEN_URL+ "/user/info?access_token=" + access_token +"&openid="+openId;
			//String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;
			httpclient =wrapClient(httpclient);
			HttpPost httppost = new HttpPost(url);
			httppost.setHeader("Connection", "close");
			
			
//			try {
//				InputStream stream = new ByteArrayInputStream(reqJson.toString().getBytes("UTF-8"));
//				HttpEntity reqEty = new InputStreamEntity(stream, reqJson.toString().getBytes("UTF-8").length);
//				httppost.setEntity(reqEty);
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
			
			log.info("向微信服务器发送请求");
			StringBuffer buffer = new StringBuffer();
			InputStream is  = null;
			BufferedReader in = null;
			try {
				HttpResponse response = httpclient.execute(httppost);
				// 解析返回结果
				HttpEntity rspEntity = response.getEntity();
				if (rspEntity != null) {
					is = rspEntity.getContent();
					in = new BufferedReader(new InputStreamReader(is, "UTF-8"));
					String line = "";
					while ((line = in.readLine()) != null) {
						buffer.append(line);
					}
				}
               log.info("返回结果:"+buffer);
				if (rspEntity.isStreaming()) {
					EntityUtils.consume(rspEntity);
				}
			} catch (Exception e) {
				//log.error("用户:【"+str_wxno[i]+"】生日祝福失败。错误原因：" + e.toString());
			}finally{ 
				if(in !=null){
	                try {
	                	in.close();
	                } catch (IOException e) {
	                      e.printStackTrace();
	                }
	          }
		         if(is !=null){
		                try {
		                	is.close();
		                } catch (IOException e) {
		                      e.printStackTrace();
		                }
		          }
		    }
			
			String returnStr = "[" + buffer + "]";
			log.info("接收的返回数据转换为字符串是：" + returnStr);
			//reqJson.delete(0, reqJson.length());//重置 reqJson 清空
		}
		
		
	  public static HttpClient wrapClient(HttpClient base) {
          try {
                  SSLContext ctx = SSLContext.getInstance("TLS");
                  X509TrustManager tm = new X509TrustManager() {
                          public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {}
                          public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {}
                          public X509Certificate[] getAcceptedIssuers() {
                                  return null;
                          }
                  };
                  ctx.init(null, new TrustManager[]{tm}, null);
                  SSLSocketFactory ssf = new SSLSocketFactory(ctx);
                  ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                  ClientConnectionManager ccm = base.getConnectionManager();
                  SchemeRegistry sr = ccm.getSchemeRegistry();
                  sr.register(new Scheme("https", ssf, 443));
                  return new DefaultHttpClient(ccm, base.getParams());
          } catch (Exception ex) {
                  ex.printStackTrace();
                  return null;
          }
	  }
	  public static void main(String[] args) {
		  String str_wxnos="or1vVwGNbhgdx1zwZw6XrGDuQE8M";
			String title="温馨提醒";
			String content="亲，您的五元介绍现金券，7天后将过期哦！";
			String picUrl="http://wx.qlogo.cn/mmopen/WRXrB3DsZ4EV0nEZBqxemk7yxJCIUz627p6tXJrd7P50PQWbvyTccFKenNWLCgO4PmnjrZHTAQl754B1642WeE09uCOIxw3Q/0";
			String postUrl="wx.fy135.com/wechat/coupon/couponList.jhtml";
			String access_token=getAccessToken();
			System.out.println(access_token);
			WeChatSendMessage.sendNew(str_wxnos,title, content, picUrl, postUrl,"MCV43MSeZ7y-uf5BTWFTpGxlelLVZy25CuzEduYt4Vv-8eKRo7c28kvJV-qGvM7Hag_awAiHRUZOP1vhnp8RmWF5qz8ivdO3M-m2D8tepNEISpHcFoj3V_gLvpjRCiGqCNAjAAAFQD");
	}
}
